<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="utf-8">
  <th:block th:include="include :: header('')"/>
  <style>
    p {
      margin: 0;
    }

    i {
      display: none;
    }

    .content {
      width: 100%;
      display: flex;
      align-items: flex-start;
      justify-content: flex-start;
    }

    .content-left {
      flex: 3;
      background-color: white;
      box-shadow: 6px 0 6px 0 #ddd;
    }

    .content-right {
      flex: 2;
      background-color: #f5f5f5;
    }

    .constant-field {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 15px;
      border-bottom: 1px solid #eee;
    }

    .constant, .field {
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }

    .constant > span, .field > span {
      font-size: 14px;
      color: #333;
    }

    .constant > input, .field > input {
      border: 1px solid #3c8dbc;
      border-radius: 4px;
      background: #f5f5f5;
      outline: none;
      height: 30px;
      width: 100px;
      margin-left: 10px;
      text-align: center;
    }

    .constant > p, .field > p {
      width: 50px;
      height: 30px;
      background-color: #3c8dbc;
      border-radius: 4px;
      font-size: 14px;
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-left: 10px;
      cursor: pointer;
    }

    .power {
      padding: 15px;
      border-bottom: 1px solid #eee;
    }

    .power-item {
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }

    .power-item-base, .power-item-power {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      flex: 1;
    }

    .power-item-base > span, .power-item-power > span {
      font-size: 14px;
      color: #333;
    }

    .power-item-base > input, .power-item-power > input {
      border: 1px solid #3c8dbc;
      border-radius: 4px;
      background: #f5f5f5;
      outline: none;
      height: 30px;
      width: 100px;
      margin-left: 10px;
      text-align: center;
    }

    .power-item-base > img, .power-item-power > img {
      width: 12px;
      height: auto;
    }

    .power-item-base-area, .power-item-power-area {
      width: 200px;
      height: 30px;
      margin-left: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .power-item-base-area > p, .power-item-power-area > p {
      padding-right: 5px;
      padding-left: 5px;
      border-radius: 5px;
      border: 1px solid #3c8dbc;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      color: #333;
    }

    .power-name {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      margin-top: 15px;
    }

    .power-name > span {
      font-size: 14px;
      color: #333;
      margin-right: 10px;
    }

    .power-name > input {
      border: 1px solid #3c8dbc;
      border-radius: 4px;
      background: #f5f5f5;
      outline: none;
      height: 30px;
      width: 150px;
      margin-right: 10px;
      text-align: center;
    }

    .power-name > p {
      width: 50px;
      height: 30px;
      background-color: #3c8dbc;
      border-radius: 4px;
      font-size: 14px;
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }

    .combine {
      padding: 15px;
      border-bottom: 1px solid #eee;
    }

    .combine-title {
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }

    .combine-title > p {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }

    .combine-title > img {
      width: 12px;
      height: auto;
    }

    .combine-area {
      margin-top: 15px;
      width: 100%;
      height: 120px;
      border: 1px solid #eee;
      display: flex;
      flex-wrap: wrap;
      align-content: flex-start;
      overflow-y: auto;
      padding-bottom: 10px;
    }

    .combine-area > p {
      padding-right: 5px;
      padding-left: 5px;
      border-radius: 5px;
      border: 1px solid #3c8dbc;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin: 10px 0 0 10px;
      font-size: 14px;
      color: #333;
    }

    .combine-area > p > img {
      width: 14px;
      height: auto;
      margin-left: 5px;
    }

    .combine-name {
      margin-top: 15px;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }

    .combine-name > span {
      font-size: 14px;
      color: #333;
      margin-right: 10px;
    }

    .combine-name > input {
      border: 1px solid #3c8dbc;
      border-radius: 4px;
      background: #f5f5f5;
      outline: none;
      height: 30px;
      width: 150px;
      margin-right: 10px;
      text-align: center;
    }

    .combine-name > p {
      width: 50px;
      height: 30px;
      background-color: #3c8dbc;
      border-radius: 4px;
      font-size: 14px;
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }

    .compare {
      padding: 15px;
      border-bottom: 1px solid #eee;
    }

    .compare-title {
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }

    .compare-title > p {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }

    .compare-title > img {
      width: 12px;
      height: auto;
    }

    table {
      margin-bottom: 0 !important;
      margin-top: 15px;
      width: 100%;
    }

    table thead tr th {
      background-color: #f0f7ff;
      font-size: 14px;
      font-weight: bold;
      color: #333;
      text-align: center;
      width: 72px;
    }

    table tbody tr td {
      font-size: 14px;
      color: #333;
      cursor: pointer;
      text-align: center;
    }

    table tbody tr td > div {
      width: 160px;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    table tbody tr td > div > input {
      width: 100%;
      height: 100%;
      border: 1px solid #3c8dbc;
      border-radius: 4px;
      background: #f5f5f5;
      outline: none;
      text-align: center;
    }

    table tbody tr td > div > p {
      padding-right: 5px;
      padding-left: 5px;
      border-radius: 5px;
      border: 1px solid #3c8dbc;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      color: #333;
    }

    table tbody tr td > div > p > img {
      width: 14px;
      height: auto;
      margin-left: 5px;
    }

    table tbody tr td > img {
      width: 14px;
      height: auto;
    }

    table tbody tr td > span {
      width: 50px;
      height: 30px;
      background-color: #3c8dbc;
      border-radius: 4px;
      font-size: 14px;
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }

    .table-bordered > thead > tr > th, .table-bordered > tbody > tr > th, .table-bordered > tfoot > tr > th, .table-bordered > thead > tr > td, .table-bordered > tbody > tr > td, .table-bordered > tfoot > tr > td {
      border: 1px solid #3c8dbc;
      vertical-align: middle;
      text-align: center;
    }

    table > thead > tr > th, table > tbody > tr > th, table > tfoot > tr > th, table > thead > tr > td, table > tbody > tr > td, table > tfoot > tr > td {
      padding: 5px;
    }

    .compare-name {
      margin-top: 15px;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }

    .compare-name > span {
      font-size: 14px;
      color: #333;
      margin-right: 10px;
    }

    .compare-name > input {
      border: 1px solid #3c8dbc;
      border-radius: 4px;
      background: #f5f5f5;
      outline: none;
      height: 30px;
      width: 150px;
      margin-right: 10px;
      text-align: center;
    }

    .compare-name > p {
      width: 50px;
      height: 30px;
      background-color: #3c8dbc;
      border-radius: 4px;
      font-size: 14px;
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }

    .custom {
      padding: 15px;
    }

    .custom > p {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }

    .custom > textarea {
      width: 100%;
      height: 120px;
      resize: none;
      border: 1px solid #eee;
      outline: none;
      font-size: 14px;
      color: #333;
      margin-top: 15px;
    }

    .custom-name {
      margin-top: 15px;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }

    .custom-name > span {
      font-size: 14px;
      color: #333;
      margin-right: 10px;
    }

    .custom-name > input {
      border: 1px solid #3c8dbc;
      border-radius: 4px;
      background: #f5f5f5;
      outline: none;
      height: 30px;
      width: 150px;
      margin-right: 10px;
      text-align: center;
    }

    .custom-name > p {
      width: 50px;
      height: 30px;
      background-color: #3c8dbc;
      border-radius: 4px;
      font-size: 14px;
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }

    .btn-clear {
      margin-left: 10px;
      background-color: white !important;
      color: #ff4c4c !important;
      border: 1px solid #ff4c4c !important;
    }

    .temporary {
      padding: 15px;
      position: relative;
    }

    .temporary-title {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }

    .temporary-area {
      width: 100%;
      height: 250px;
      display: flex;
      flex-wrap: wrap;
      align-content: flex-start;
      overflow-y: auto;
      padding-bottom: 10px;
    }

    .temporary-area > p {
      padding-right: 5px;
      padding-left: 5px;
      border-radius: 5px;
      border: 1px solid #3c8dbc;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin: 10px 0 0 10px;
      font-size: 14px;
      color: #333;
    }

    .temporary-area > p > img {
      width: 14px;
      height: auto;
      margin-left: 5px;
    }

    .confirm {
      margin: 0 15px;
      padding: 15px;
      background-color: white;
      border: 1px solid #eee;
    }

    .confirm-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .confirm-title > div {
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }

    .confirm-title > div > p {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }

    .confirm-title > div > img {
      width: 12px;
      height: auto;
    }

    .confirm-title > p {
      border: 1px solid #ff4c4c;
      background-color: white;
      color: #ff4c4c;
      font-size: 14px;
      width: 50px;
      height: 30px;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }

    .confirm-area {
      height: 200px;
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      align-content: flex-start;
      overflow-y: auto;
      padding-bottom: 10px;
    }

    .confirm-area > p {
      padding-right: 5px;
      padding-left: 5px;
      border-radius: 5px;
      border: 1px solid #3c8dbc;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin: 10px 0 0 10px;
      font-size: 14px;
      color: #333;
    }

    .confirm-area > p > img {
      width: 14px;
      height: auto;
      margin-left: 5px;
    }

    .confirm-operate {
      margin-top: 15px;
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }

    .confirm-operate > p {
      width: 50px;
      height: 30px;
      background-color: #3c8dbc;
      border-radius: 4px;
      font-size: 14px;
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }

    .preview {
      margin: 15px 15px 0 15px;
      height: 200px;
      padding: 15px;
      background-color: white;
    }

    .preview > p {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }

    .preview > textarea {
      width: 100%;
      height: 100%;
      padding: 10px;
      resize: none;
      border: none;
      outline: none;
      font-size: 14px;
      color: #333;
    }
  </style>
</head>
<body>
<div class="content">
  <div class="content-left">
    <div class="constant-field">
      <div class="constant">
        <span>常量</span>
        <input type="number" name="constant" ondragover="return false;"/>
        <p onclick="generateInputItem(this)">暂存</p>
      </div>
      <div class="field">
        <span>字段</span>
        <input type="text" name="field" ondragover="return false;"/>
        <p onclick="generateInputItem(this)">暂存</p>
      </div>
    </div>
    <div class="power">
      <div class="power-item">
        <div class="power-item-base" ondragover="return false;">
          <span>底</span>
          <input type="number" id="power-base-input"
                 oninput="clearDragItem(this)" />
          <img src="./images/drag.png"　／>
          <div class="power-item-base-area" ondrop="drop(event,'power-item-base-area')"
               ondragover="cancelDefault(event)"></div>
        </div>
        <div class="power-item-power" ondragover="return false;">
          <span>幂</span>
          <input type="number" id="power-input" oninput="clearDragItem(this)"/>
          <img src="./images/drag.png"　／>
          <div class="power-item-power-area" ondrop="drop(event,'power-item-power-area')"
               ondragover="cancelDefault(event)"></div>
        </div>
      </div>
      <div class="power-name">
        <span>名称</span>
        <input type="text" placeholder="请输入名称" id="powerName" ondragover="return false;"/>
        <p onclick="powerConfirm()">暂存</p>
      </div>
    </div>
    <div class="combine" ondragover="return false;">
      <div class="combine-title">
        <p>组合公式</p>
        <img src="./images/drag.png" />
      </div>
      <div class="combine-area" ondrop="drop(event,'combine-area')" ondragover="cancelDefault(event)"></div>
      <div class="combine-name">
        <span>名称</span>
        <input type="text" placeholder="请输入名称" id="combineName"/>
        <p onclick="confirmCombine()">暂存</p>
        <p class="btn-clear" onclick="clearCombineArea()">清空</p>
      </div>
    </div>
    <div class="compare">
      <div class="compare-title">
        <p>比较组</p>
        <img src="./images/drag.png">
      </div>
      <table class="table" id="compareTable">
        <thead>
        <tr>
          <th>比较项</th>
          <th>起始</th>
          <th>结束</th>
          <th>结果值</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        </tbody>
      </table>
      <div class="compare-name">
        <span>名称</span>
        <input type="text" placeholder="请输入名称" ondragover="return false;"/>
        <p onclick="confirmCompare(this)">暂存</p>
      </div>
    </div>
    <div class="custom">
      <p>自定义公式</p>
      <textarea id="customFormula" ondragover="return false;"></textarea>
      <div class="custom-name">
        <span>名称</span>
        <input type="text" placeholder="请输入名称" id="customName" ondragover="return false;"/>
        <p onclick="confirmCustomFormula()">暂存</p>
        <p class="btn-clear" onclick="clearCustomFormula()">清空</p>
      </div>
    </div>
  </div>
  <div class="content-right">
    <div class="temporary">
      <p class="temporary-title">暂存选项</p>
      <div class="temporary-area">
        <p draggable="true" ondragstart="drag(event)"><span>+</span><i>{"type":"00","name":"+","value":"+","orderNum":"1"}</i>
        </p>
        <p draggable="true" ondragstart="drag(event)"><span>-</span><i>{"type":"00","name":"-","value":"-","orderNum":"1"}</i>
        </p>
        <p draggable="true" ondragstart="drag(event)"><span>*</span><i>{"type":"00","name":"*","value":"*","orderNum":"1"}</i>
        </p>
        <p draggable="true" ondragstart="drag(event)"><span>/</span><i>{"type":"00","name":"/","value":"/","orderNum":"1"}</i>
        </p>
        <p draggable="true" ondragstart="drag(event)"><span>(</span><i>{"type":"00","name":"(","value":"(","orderNum":"1"}</i>
        </p>
        <p draggable="true" ondragstart="drag(event)"><span>)</span><i>{"type":"00","name":")","value":")","orderNum":"1"}</i>
        </p>
      </div>
    </div>
    <div class="confirm" ondragover="return false;">
      <div class="confirm-title">
        <div><p>确定选项</p>
          <img src="./images/drag.png">
        </div>
        <p onclick="clearConfirmFormula()">清空</p>
      </div>
      <div class="confirm-area" ondrop="drop(event,'confirm-area')" ondragover="cancelDefault(event)">

      </div>
      <div class="confirm-operate">
        <p onclick="submitComfirmFormula()">提交</p>
        <p style="margin-left: 10px" onclick="translateFormula()">翻译</p>
      </div>
    </div>
    <div class="preview">
      <p>公式翻译预览</p>
      <textarea readonly id="translatePreview" ondragover="return false;"></textarea>
    </div>
  </div>
</div>

<th:block th:include="include :: footer"/>

<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>

<script th:inline="javascript">

  // url参数
  let urlParams = {
    id: '',
    base_url: ''
  }

  // 计算id
  let calculateId = ''

  var config = {
    constant: "00",//常量
    formula: "01",//公式
    field: "02",//字段
    methodValue: "03",//方法取值
    power: "04",//幂次方
    compare: "05"//比较值
  };

  var updateCalculationFormulaUrl = "";
  var formulaId = "";
  //riskId和productId保存比较项需要；
  var riskId = "";
  var productId = "";

  let updateUrl = '';

  // 初始化参数
  const initParam = {
    formulaId: "",
    formulaList: "",
    updateUrl: "",
    formula: "",
    id: "",
    cashCompareList: ""
  };

  $(function () {
    //当前框架已禁止拖动了，现在解禁
    document.ondragstart = function () {
      return true;
    };

    // 1. 解析参数
    getUrlInit();

    // 2. 根据险种id获取参数
    getInitParams();
  });

  // 获取url中的参数
  function getUrlInit() {
    let query  = window.location.search.substring(1);
    let params = query.split("&");

    for(const param of params) {
      const arr = param.split("=");
      // initParam[arr[0]] = arr[1];

      urlParams[arr[0]] = arr[1];
    }

  };

  function getInitParams() {
    const type = urlParams.type || null


    $.ajax({
      url: `${urlParams.base_url}/pm/formulaConfig/initFormula/${type}`,
      type: "post",
      contentType: "application/json",
      headers: {
        'Authorization': 'Bearer ' + getCookie('Admin-Token')
      },
      data: JSON.stringify({
        id: urlParams.id,
        formulaId: urlParams.calculateId
      }),
      success: function (res) {
        console.log('请求结果res为:', res);

        initParam.formulaId   = res.formulaId;
        initParam.formulaList = res.formulaList;
        initParam.updateUrl   = res.updateUrl;
        initParam.formula     = res.formula;
        initParam.id          = res.id;
        initParam.cashCompareList = res.cashCompareList;
        console.log(initParam, '--initParam-')
        // 进行初始化操作
        init();
      }
    });
  };

  // 获取cookie的值
  function getCookie(cookie_name) {
    var allcookies = document.cookie;
    //索引长度，开始索引的位置
    var cookie_pos = allcookies.indexOf(cookie_name);

    // 如果找到了索引，就代表cookie存在,否则不存在
    if (cookie_pos != -1) {
      // 把cookie_pos放在值的开始，只要给值加1即可
      //计算取cookie值得开始索引，加的1为“=”
      cookie_pos = cookie_pos + cookie_name.length + 1;
      //计算取cookie值得结束索引
      var cookie_end = allcookies.indexOf(";", cookie_pos);
      if (cookie_end == -1) {
        cookie_end = allcookies.length;
      }
      //得到想要的cookie的值
      var value = unescape(allcookies.substring(cookie_pos, cookie_end));
    }
    return value;
  };

  //初始化
  function init() {
    // var formula = `[[${formula}]]`;
    // var formulaList = `[[${formulaList}]]`;
    // var cashCompareList = `[[${cashCompareList}]]`;
    // riskId = `[[${riskId}]]`;
    // productId = `[[${productId}]]`;
    // updateCalculationFormulaUrl = `[[${updateUrl}]]`;
    // formulaId = `[[${formulaId}]]`;

    let {formula, formulaList, cashCompareList} = initParam;
    riskId = initParam?.riskId;
    productId = initParam?.productId;
    updateCalculationFormulaUrl = initParam?.updateUrl;
    formulaId = initParam?.formulaId;

    //清空比较组表格并设置默认值
    clearCompareTable();

    //回显计算公式翻译
    if(!isEmpty(formula)) {
      $("#translatePreview").val(formatJson(formula));
    }
    //计算公式回显
    var formulaArray = formula && JSON.parse(formula);

    // console.log('formulaArray为', formulaArray);

    var formulaHtml = "";
    if(!isEmpty(formulaArray)){
      for (var i = 0; i < formulaArray.length; i++) {
        formulaHtml = formulaHtml + "<p><span>" + formulaArray[i].name + "</span><img src=\"./images/btn_clear.png\" onclick=\"deleteItem(this)\"><i>" + JSON.stringify(formulaArray[i]) + "</i></p>";
      }
      $(".confirm-area").append(formulaHtml);
    }
    //初始化默认公式
    var defaultFormulaHtml = "";
    var formulaJsonObject = null;
    if(!isEmpty(formulaList)){
      for (var i = 0; i < formulaList.length; i++) {
        formulaJsonObject = JSON.parse(formulaList[i].value);
        defaultFormulaHtml = defaultFormulaHtml + "<p draggable=\"true\" ondragstart=\"drag(event)\"><span>" + formulaJsonObject.name + "</span><i>" + formulaList[i].value + "</i></p>";
      }


      $(".temporary-area").append(defaultFormulaHtml);
    }
    //确定的公式选项也要回显至暂存栏位中
    formulaHtml = "";
    if(!isEmpty(formulaArray)){
      for (var i = 0; i < formulaArray.length; i++) {
        formulaHtml = formulaHtml + "<p class='add' draggable=\"true\" ondragstart=\"drag(event)\"><span>" + formulaArray[i].name + "</span><img src=\"./images/btn_clear.png\" onclick=\"deleteItem(this)\"><i>" + JSON.stringify(formulaArray[i]) + "</i></p>";
      }
      $(".temporary-area").append(formulaHtml);
    }

    console.log('cashCompareList为', cashCompareList);

    //回显比较组信息
    if (!isEmpty(cashCompareList)) {
      var compareHtml = "";
      var compareJsonObject = null;
      var compareName = "";
      for (var i = 0; i < cashCompareList.length; i++) {
        compareName = cashCompareList[i].name;
        compareJsonObject = new Object();
        compareJsonObject.type = config.compare;
        compareJsonObject.name = compareName;
        compareJsonObject.value = cashCompareList[i]?.groupId;
        compareJsonObject.orderNum = (i + 1) + "";
        compareHtml = compareHtml + "<p draggable='true' ondragstart='drag(event)'><span>" + compareName + "</span><img src=\"./images/btn_clear.png\" onclick=\"deleteCompareGroup(this)\"><i>" + JSON.stringify(compareJsonObject) + "</i></p>";
      }

      $(".temporary-area").append(compareHtml);
    }
  }

  //删除容器中指定的项目
  function deleteItem(self) {
    $(self).parent().remove();
  }

  //删除之前配置的比较组，调用接口删除，需要confirm确认
  function deleteCompareGroup(self) {
    const groupId = JSON.parse($(self).next().text()).value;

    const flag = window.confirm("是否删除吗?");
    if(flag) {
      var param = {
        groupId: groupId
      };
      $.ajax({
        url: urlParams.base_url + "/pm/saasCashCompare/removeByGroup",
        type: "post",
        contentType: "application/json",
        headers: {
          'Authorization': 'Bearer ' + getCookie('Admin-Token')
        },
        data: JSON.stringify(param),
        success: function (res) {
          if (res.code == 200) {
            //后台删除成功就移除页面上的元素
            $(self).parent().remove();
          }
        }
      });
    }
  }

  //空值判断
  function isEmpty(v) {
    switch (typeof v) {
      case 'undefined':
        return true;
      case 'string':
        if (v.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/g, '').length == 0) return true;
        break;
      case 'number':
        if (0 === v || isNaN(v)) return true;
        break;
      case 'object':
        if (null === v || v.length === 0) return true;
        for (var i in v) {
          return false;
        }
        return true;
    }
    return false;
  }

  //常量和字段暂存生成项目
  function generateInputItem(self) {
    var input = $(self).prev()[0];
    var inputName = input.name;
    var inputValue = input.value;
    if (!isEmpty(inputValue)) {
      var type = config[inputName];
      var jsonStr = "{\"type\":\"" + type + "\",\"name\":\"" + inputValue + "\",\"value\":\"" + inputValue + "\",\"orderNum\":\"1\"}";
      $(".temporary-area").append("<p class='add' draggable='true' ondragstart='drag(event)'><span>" + inputValue + "</span><img src=\"./images/btn_clear.png\" onclick=\"deleteItem(this)\"><i>" + jsonStr + "</i></p>");
      input.value = "";
    }
  }

  //幂次方生成项目;orderNum:1---幂次方的底数；orderNum:3---幂次方的幂数；orderNum:2---幂次方符号
  function powerConfirm() {
    //底和幂中input值和p项目有且只有一个
    var powerBase = false;//底校验标志
    var power = false;//幂校验标志
    var powerBaseValue = "";//底value值
    var powerValue = "";//幂value值
    var powerBaseObject = "";//底对象
    var powerObject = "";//幂对象
    var json = "";//填写完信息生成的幂次方json

    //底
    var powerBaseInput = $("#power-base-input").val();
    var pTag = $(".power-item-base-area").children("p");
    //底项目没有input值
    if (isEmpty(powerBaseInput)) {
      if (pTag.length == 1) {
        powerBase = true;
        powerBaseValue = pTag.children("i").text();
        powerBaseObject = JSON.parse(powerBaseValue);
        powerBaseObject.orderNum = "1";
      } else {
        powerBase = false;
      }
    }
    //底项目中有input值
    else {
      if (pTag.length == 0) {
        powerBase = true;
        //input框只能输常量类型，不能输字段
        powerBaseObject = {
          "type": config.constant,
          "name": powerBaseInput,
          "value": powerBaseInput,
          "orderNum": "1"
        };
      } else {
        powerBase = false;
      }
    }
    var powerInput = $("#power-input").val();
    pTag = $(".power-item-power-area").children("p");
    //幂项目中没有input值
    if (isEmpty(powerInput)) {
      if (pTag.length == 1) {
        power = true;
        powerValue = pTag.children("i").text();
        powerObject = JSON.parse(powerValue);
        powerObject.orderNum = "3";
      } else {
        power = false;
      }
    }
    //幂项目中有input值
    else {
      if (pTag.length == 0) {
        power = true;
        //input框只能输常量类型，不能输字段
        powerObject = {"type": config.constant, "name": powerInput, "value": powerInput, "orderNum": "3"};
      } else {
        power = false;
      }
    }

    var powerName = $("#powerName").val();
    if (!isEmpty(powerName) && powerBase && power) {
      var type = config.power;
      var arr = [];
      arr.push(powerBaseObject);
      arr.push(powerObject);
      arr.push({"type": config.constant, "name": "^", "value": "^", "orderNum": "2"});
      var obj = {type: type, name: powerName, value: JSON.stringify(arr), orderNum: "1"};
      $(".temporary-area").append("<p class='add' draggable='true' ondragstart='drag(event)'><span>" + powerName + "</span><img src=\"./images/btn_clear.png\" onclick=\"deleteItem(this)\"><i>" + JSON.stringify(obj) + "</i></p>");
    }
    //清空幂次方输入项中的数据
    $("#powerName").val("");
    $("#power-base-input").val("");
    $("#power-input").val("");
    $(".power-item-base-area").children("p").remove();
    $(".power-item-power-area").children("p").remove();
  }

  //添加比较组里面的项目
  function addCompareItem(self) {
    var compare = false;//比较项标志
    var compareStart = false;//起始值标志
    var compareEnd = false;//结束值标志
    var compareResult = false;//结果值标志
    var tr = $(self).parent().parent();
    var compareInput = tr.children().eq(0).find("input").val();//比较项input值
    var compareStartInput = tr.children().eq(1).find("input").val();//起始input值
    var compareEndInput = tr.children().eq(2).find("input").val();//结束input值
    var compareResultInput = tr.children().eq(3).find("input").val();//结果值input值
    var pTag = null;//子项p标签

    //比较项
    pTag = tr.children().eq(0).children("div").children("p");
    if (isEmpty(compareInput)) {
      if (pTag.length == 1) {
        compare = true;
      } else {
        compare = false;
      }
    } else {
      if (pTag.length == 0) {
        compare = true;
      } else {
        compare = false;
      }
    }

    //起始项
    pTag = tr.children().eq(1).children("div").children("p");
    if (isEmpty(compareStartInput)) {
      if (pTag.length == 1) {
        compareStart = true;
      } else {
        compareStart = false;
      }
    } else {
      if (pTag.length == 0) {
        compareStart = true;
      } else {
        compareStart = false;
      }
    }

    //结束项
    pTag = tr.children().eq(2).children("div").children("p");
    if (isEmpty(compareEndInput)) {
      if (pTag.length == 1) {
        compareEnd = true;
      } else {
        compareEnd = false;
      }
    } else {
      if (pTag.length == 0) {
        compareEnd = true;
      } else {
        compareEnd = false;
      }
    }

    //结果值项
    pTag = tr.children().eq(3).children("div").children("p");
    if (isEmpty(compareResultInput)) {
      if (pTag.length == 1) {
        compareResult = true;
      } else {
        compareResult = false;
      }
    } else {
      if (pTag.length == 0) {
        compareResult = true;
      } else {
        compareResult = false;
      }
    }

    //起始项和终止项必须有一项有值
    if (compare && compareResult && (compareStart || compareEnd)) {
      $(self).parent().append("<img onclick='deleteCompareItem(this)' src=\"./images/btn_delete.png\">");
      //确认一行比较项后，要将该行重置为不可拖放
      var div = $(self).parents("tr").children().children("div");
      div.each(function (index, item) {
        $(item).removeAttr("ondrop");
        $(item).removeAttr("ondragover");
        $(item).attr("ondragover", "return false;");
      });
      $(self).remove();
      $("#compareTable tbody").append('<tr ondragover="return false;"><td><div ondrop="drop(event,\'compare\')" ondragover="cancelDefault(event)"><input type="number" ondragover="return false;"></div></td><td><div ondrop="drop(event,\'compareStart\')" ondragover="cancelDefault(event)"><input type="number" ondragover="return false;"></div></td><td><div ondrop="drop(event,\'compareEnd\')" ondragover="cancelDefault(event)"><input type="number" ondragover="return false;"></div></td><td><div ondrop="drop(event,\'compareResult\')" ondragover="cancelDefault(event)"><input type="number" ondragover="return false;"></div></td><td><span onclick="addCompareItem(this)">添加</span></td></tr>');
    }
  }

  //清除比较组表格中的数据
  function clearCompareTable() {
    $("#compareTable tbody").html("");
    $("#compareTable tbody").append('<tr ondragover="return false;"><td><div ondrop="drop(event,\'compare\')" ondragover="cancelDefault(event)"><input type="number" ondragover="return false;"></div></td><td><div ondrop="drop(event,\'compareStart\')" ondragover="cancelDefault(event)"><input type="number" ondragover="return false;"></div></td><td><div ondrop="drop(event,\'compareEnd\')" ondragover="cancelDefault(event)"><input type="number" ondragover="return false;"></div></td><td><div ondrop="drop(event,\'compareResult\')" ondragover="cancelDefault(event)"><input type="number" ondragover="return false;"></div></td><td><span onclick="addCompareItem(this)">添加</span></td></tr>');
  }

  //删除一行table中的比较项
  function deleteCompareItem(self) {
    $(self).parents("tr").remove();
  }

  //确认提交比较组,提交前先判断有没有填写名称和添加比较项
  function confirmCompare(self) {
    var inputName = $(self).prev().val();
    var tr = $("#compareTable tbody tr");

    var len = tr.length;
    if (isEmpty(inputName) || len < 2) {
      return false;
    }
    var arr = [];
    var obj = null;
    var compareInput = "";//比较项input值
    var compareStartInput = "";//起始input值
    var compareEndInput = "";//结束input值
    var compareResultInput = "";//结果值input值
    var pTag = null;//子项p标签
    var compareJsonObject = null;
    var compareStartJsonObject = null;
    var compareEndJsonObject = null;
    var compareResultJsonObject = null;
    tr.each(function (index, item) {
      //比较组最后一行为操作行，跳过
      if (index == len - 1) {
        return true;
      }
      compareInput = $(item).children().eq(0).find("input").val();
      compareStartInput = $(item).children().eq(1).find("input").val();
      compareEndInput = $(item).children().eq(2).find("input").val();
      compareResultInput = $(item).children().eq(3).find("input").val();

      //比较项
      pTag = $(item).children().eq(0).children("div").children("p");
      if (isEmpty(compareInput)) {
        if (pTag.length == 1) {
          compareJsonObject = JSON.parse(pTag.children("i").text());
        }
      } else {
        if (pTag.length == 0) {
          compareJsonObject = {
            "type": config.constant,
            "name": compareInput,
            "value": compareInput,
            "orderNum": "1"
          };
        }
      }

      //起始项
      pTag = $(item).children().eq(1).children("div").children("p");
      if (isEmpty(compareStartInput)) {
        if (pTag.length == 1) {
          compareStartJsonObject = JSON.parse(pTag.children("i").text());
        }
      } else {
        if (pTag.length == 0) {
          compareStartJsonObject = {
            "type": config.constant,
            "name": compareStartInput,
            "value": compareStartInput,
            "orderNum": "1"
          };
        }
      }

      //结束项
      pTag = $(item).children().eq(2).children("div").children("p");
      if (isEmpty(compareEndInput)) {
        if (pTag.length == 1) {
          compareEndJsonObject = JSON.parse(pTag.children("i").text());
        }
      } else {
        if (pTag.length == 0) {
          compareEndJsonObject = {
            "type": config.constant,
            "name": compareEndInput,
            "value": compareEndInput,
            "orderNum": "1"
          };
        }
      }

      //结果值项
      pTag = $(item).children().eq(3).children("div").children("p");
      if (isEmpty(compareResultInput)) {
        if (pTag.length == 1) {
          compareResultJsonObject = JSON.parse(pTag.children("i").text());
        }
      } else {
        if (pTag.length == 0) {
          compareResultJsonObject = {
            "type": config.constant,
            "name": compareResultInput,
            "value": compareResultInput,
            "orderNum": "1"
          };
        }
      }

      //起始项和终止项没有值的时候传空串
      if (isEmpty(compareStartJsonObject)) {
        compareStartJsonObject = "";
      } else {
        compareStartJsonObject = "[" + JSON.stringify(compareStartJsonObject) + "]";
      }
      if (isEmpty(compareEndJsonObject)) {
        compareEndJsonObject = "";
      } else {
        compareEndJsonObject = "[" + JSON.stringify(compareEndJsonObject) + "]";
      }
      compareJsonObject = "[" + JSON.stringify(compareJsonObject) + "]";
      compareResultJsonObject = "[" + JSON.stringify(compareResultJsonObject) + "]";
      obj = new Object();
      obj.riskId = initParam?.id;
      obj.productId = initParam?.productId;
      obj.name = inputName;
      obj.compareValue = compareJsonObject;
      obj.startValue = compareStartJsonObject;
      obj.endValue = compareEndJsonObject;
      obj.value = compareResultJsonObject;
      arr.push(obj);
    });

    //调接口，返回groupId；然后拼接到容器中
    $.ajax({
      url: urlParams.base_url  + '/pm/saasCashCompare/addSaveList',
      type: "post",
      headers: {
        'Authorization': 'Bearer ' + getCookie('Admin-Token')
      },
      contentType: "application/json",
      data: JSON.stringify(arr),
      success: function (res) {
        if (res.code == 200) {
          var object = new Object();
          object.type = config.compare;
          object.name = inputName;
          object.value = res.data;
          object.orderNum = "1";
          $(".temporary-area").append("<p class='add' draggable='true' ondragstart='drag(event)'><span>" + inputName + "</span><img src=\"./images/btn_clear.png\" onclick=\"deleteCompareGroup(this)\"><i>" + JSON.stringify(object) + "</i></p>");
          //清空比较组表格中的数据
          clearCompareTable();
          $(self).prev().val("");
        }
      }
    });
  };

  //拖动处理 设置被拖数据的数据类型和值
  function drag(ev) {
    console.log('ev为:',ev);
    console.log('target为', ev.target);

    //当前拖拽标签的索引，作为取数据的标识符
    ev.dataTransfer.setData("Text", $(ev.target).index());
  }

  //ondragover 事件规定在何处放置被拖动的数据。默认地，无法将数据/元素放置到其他元素中。如果需要设置允许放置，我们必须阻止对元素的默认处理方式。
  function cancelDefault(ev) {
    ev.preventDefault();
  }

  //当放置被拖数据时
  function drop(ev, target) {

    ev.preventDefault();
    var tagIndex = ev.dataTransfer.getData("Text");
    var temporaryArea = $(".temporary-area");
    //幂次方
    if (target == "power-item-base-area" || target == "power-item-power-area") {
      if (($(ev.target)[0].nodeName == "DIV" && $(ev.target).hasClass(target)) || ($(ev.target)[0].nodeName == "P" && $(ev.target).parent().hasClass(target)) || ($(ev.target)[0].nodeName == "SPAN" && $(ev.target).parent().parent().hasClass(target))) {
        //由于div中只能存在一个拖拽的p标签元素，所以赋值之前要有判断，如果有则要先删除，再添加
        var targetElement = $("." + target);
        //当拖入p标签时，清空input框的值，因为p标签和input值有且只有一个
        targetElement.parent().children("input").val("");
        var pTag = targetElement.children("p");
        if (pTag.length > 0) {
          pTag.remove();
        }
        var dragElement = temporaryArea.children("p").eq(tagIndex);
        targetElement.append("<p><span>" + dragElement.children("span").text() + "</span><i>" + dragElement.children("i").text() + "</i></p>");
      }
    }
    //比较组
    else if (target == "compare" || target == "compareStart" || target == "compareEnd" || target == "compareResult") {
      var targetElement = $(ev.target);
      var dragElement = temporaryArea.children("p").eq(tagIndex);
      if (targetElement[0].nodeName == "INPUT" || targetElement[0].nodeName == "P") {
        //如果拖拽目的地点元素是input，则在父级append，在删除input元素;如果拖拽目的地点元素是P，则说明已经存在P标签，也是父级append，再删除原来的P标签
        targetElement.parent().append("<p><span>" + dragElement.children("span").text() + "</span><img src=\"./images/btn_clear.png\" onclick=\"refreshCompareItem(this)\"><i>" + dragElement.children("i").text() + "</i></p>");
        targetElement.remove();
      } else if (targetElement[0].nodeName == "SPAN" || targetElement[0].nodeName == "IMG") {
        //如果拖拽的目的地点元素是span或者img，则说明之前已经存在P标签，则在p标签的父级append，再删除原来的P标签
        targetElement.parent().parent().append("<p><span>" + dragElement.children("span").text() + "</span><img src=\"./images/btn_clear.png\" onclick=\"refreshCompareItem(this)\"><i>" + dragElement.children("i").text() + "</i></p>");
        targetElement.parent().remove();
      }
    }
    //组合公式或已确定选
    else if (target == "combine-area" || target == "confirm-area") {
      var targetElement = $(ev.target);
      var dragElement = temporaryArea.children("p").eq(tagIndex);
      if (targetElement[0].nodeName == "DIV") {
        if (targetElement.hasClass(target)) {
          targetElement.append("<p><span>" + dragElement.children("span").text() + "</span><img src=\"./images/btn_clear.png\" onclick=\"deleteItem(this)\"><i>" + dragElement.children("i").text() + "</i></p>");
        }
      } else if (targetElement[0].nodeName == "P") {
        if (targetElement.parent().hasClass(target)) {
          //如果拖拽的目标地点元素是p标签，则默认添加在当前p标签的前面
          targetElement.before("<p><span>" + dragElement.children("span").text() + "</span><img src=\"./images/btn_clear.png\" onclick=\"deleteItem(this)\"><i>" + dragElement.children("i").text() + "</i></p>");
        }
      } else if (targetElement[0].nodeName == "IMG" || targetElement[0].nodeName == "SPAN") {
        if (targetElement.parent().parent().hasClass(target)) {
          //如果拖拽的目标地点元素是p标签里面的img或者span，则默认添加在当前p标签的前面
          targetElement.parent().before("<p><span>" + dragElement.children("span").text() + "</span><img src=\"./images/btn_clear.png\" onclick=\"deleteItem(this)\"><i>" + dragElement.children("i").text() + "</i></p>");
        }
      }
    }
  }

  //比较组td中拖拽过来的P标签删除操作，删除后在拼接input框;只能删除当前正在操作的tr，已经确定的tr是删除不了的
  function refreshCompareItem(self) {
    //判断依据：看当前行的操作列里面显示的是img还是添加按钮，如果是img则表示当前行是已经确认过的，否则是当前正在操作的行
    var tr = $(self).parents("tr");
    var operate = tr.children().eq(4).children();
    if (operate[0].nodeName == "SPAN") {
      $(self).parent().parent().append('<input type="text" ondragover="return false;">');
      $(self).parent().remove();
    }
  }

  //input框输入时，清空p标签
  function clearDragItem(self) {
    $(self).parent().children("div").children("p").remove();
  }

  //清空组合公式
  function clearCombineArea() {
    $(".combine-area").children("p").remove();
    $("#combineName").val("");
  }

  //确认生成组合公式
  function confirmCombine() {
    //生成前先判断组合公式名称是否有值
    var combineName = $("#combineName").val();
    var combineArea = $(".combine-area").children("p");
    var len = combineArea.length;
    if (isEmpty(combineName) || len == 0) {
      return false;
    }
    var arr = [];
    var obj = null;
    combineArea.each(function (index, item) {
      obj = JSON.parse($(item).children("i").text());
      obj.orderNum = (index + 1) + "";
      arr.push(obj);
    });
    var jsonObject = new Object();
    jsonObject.type = config.formula;
    jsonObject.name = combineName;
    jsonObject.value = JSON.stringify(arr);
    jsonObject.orderNum = "1";
    $(".temporary-area").append("<p class='add' draggable='true' ondragstart='drag(event)'><span>" + combineName + "</span><img src=\"./images/btn_clear.png\" onclick=\"deleteItem(this)\"><i>" + JSON.stringify(jsonObject) + "</i></p>");
    clearCombineArea();
  }

  //清空计算公式中拖入项目
  function clearConfirmFormula() {
    $(".confirm-area").children("p").remove();
  }

  //生成已经完成的配置公式json
  function submitComfirmFormula() {
    var dragElement = $(".confirm-area").children("p");
    //如果不存在拖动元素，则返回
    if (dragElement.length == 0) {
      return false;
    }
    var arr = [];
    var obj = null;

    dragElement.each(function (index, item) {
      obj = JSON.parse($(item).children("i").text());
      obj.orderNum = (index + 1) + "";
      arr.push(obj);
    });
    var param = {
      id: formulaId,
      value: JSON.stringify(arr),
    };

    $.ajax({
      // url: urlParams.base_url  + '/' + updateCalculationFormulaUrl,
      url: urlParams.base_url  + '/pm/saasFormula/addFormula',
      type: "post",
      contentType: "application/json",
      headers: {
        'Authorization': 'Bearer ' + getCookie('Admin-Token')
      },
      data: JSON.stringify(param),
      success: function (res) {
        if (res.code == "200") {
          // alert(res.msg);
          calculateId = res.data.formulaId
          console.log(updateCalculationFormulaUrl, '--updateCalculationFormulaUrl--')
          if (updateCalculationFormulaUrl && updateCalculationFormulaUrl !== '') {
            editFormula(calculateId)
            // window.
          } else {
            window.parent.postMessage({
              type: 'success',
              calculateId
            }, '*')
          }
          // $.modal.closeTab();
        }
      }
    });
  };

  // 插入表
  function editFormula (formulaId) {
    const param = {
      id: urlParams.id,
      formulaId: formulaId
    }
    $.ajax({
      url: urlParams.base_url  + '/' + updateCalculationFormulaUrl,
      type: "post",
      contentType: "application/json",
      headers: {
        'Authorization': 'Bearer ' + getCookie('Admin-Token')
      },
      data: JSON.stringify(param),
      success: function (res) {
        if (res.code == "200") {
          // const calculateId = res.formulaId
          window.parent.postMessage({
            type: 'success',
            calculateId: null
          }, '*')
          // $.modal.closeTab();
        }
      }
    });
  }

  //翻译计算公式
  function translateFormula() {
    var dragElement = $(".confirm-area").children("p");
    //没有拖动元素，直接返回
    if (dragElement.length == 0) {
      return false;
    }
    var arr = [];
    var obj = null;
    dragElement.each(function (index, item) {
      obj = JSON.parse($(item).children("i").text());
      obj.orderNum = (index + 1) + "";
      arr.push(obj);
    });
    $("#translatePreview").val(formatJson(JSON.stringify(arr)));
  }

  //判断某个字符串是不是json字符串
  function isJSON(str) {
    if (typeof(str) === 'string') {
      try {
        var obj = JSON.parse(str);
        if (typeof(obj) === 'object' && obj) {
          return true;
        }
        else {
          return false;
        }
      }
      catch (e) {
        return false;
      }
    }
  }

  //生成自定义输入的json项目
  function confirmCustomFormula() {
    var customName = $("#customName").val();
    var customFormula = $("#customFormula").val();
    if (isEmpty(customName) || !isJSON(customFormula)) {
      return false;
    }
    //接收的json字符串只能是对象和数组字符串
    var jsonObject = JSON.parse(customFormula);
    var jsonArray = [];
    //typeof的入参是对象和数组时都返回object，直接用length属性来判断
    if (isEmpty(jsonObject.length)) {
      jsonObject.orderNum = "1";
      jsonArray.push(jsonObject);
    } else {
      for (var i = 0; i < jsonObject.length; i++) {
        jsonObject[i].orderNum = (i + 1) + "";
      }
      jsonArray = jsonObject;
    }
    var textareaJsonObject = new Object();
    textareaJsonObject.type = config.formula;
    textareaJsonObject.name = customName;
    textareaJsonObject.value = JSON.stringify(jsonArray);
    textareaJsonObject.orderNum = "1";
    $(".temporary-area").append("<p class='add' draggable='true' ondragstart='drag(event)'><span>" + customName + "</span><img src=\"./images/btn_clear.png\" onclick=\"deleteItem(this)\"><i>" + JSON.stringify(textareaJsonObject) + "</i></p>");
    clearCustomFormula();
  }

  //清空自定义输入的json项目
  function clearCustomFormula() {
    $("#customFormula").val("");
    $("#customName").val("");
  }

  // 格式方法 公共方法
  function transitionJsonToString(jsonObj, callback) {
    // 转换后的jsonObj受体对象
    var _jsonObj = null;
    // 判断传入的jsonObj对象是不是字符串，如果是字符串需要先转换为对象，再转换为字符串，这样做是为了保证转换后的字符串为双引号
    if (Object.prototype.toString.call(jsonObj) !== "[object String]") {
      try {
        _jsonObj = JSON.stringify(jsonObj);
      } catch (error) {
        // 转换失败错误信息
        console.error('您传递的json数据格式有误，请核对...');
        console.error(error);
        callback(error);
      }
    } else {
      try {
        jsonObj = jsonObj.replace(/(\')/g, '\"');
        _jsonObj = JSON.stringify(JSON.parse(jsonObj));
      } catch (error) {
        // 转换失败错误信息
        console.error('您传递的json数据格式有误，请核对...');
        console.error(error);
        callback(error);
      }
    }
    return _jsonObj;
  }

  // callback为数据格式化错误的时候处理函数
  function formatJson(jsonObj, callback) {
    // 正则表达式匹配规则变量
    var reg = null;
    // 转换后的字符串变量
    var formatted = '';
    // 换行缩进位数
    var pad = 0;
    // 一个tab对应空格位数
    var PADDING = '    ';
    // json对象转换为字符串变量
    var jsonString = transitionJsonToString(jsonObj, callback);
    if (!jsonString) {
      return jsonString;
    }
    // 存储需要特殊处理的字符串段
    var _index = [];
    // 存储需要特殊处理的“再数组中的开始位置变量索引
    var _indexStart = null;
    // 存储需要特殊处理的“再数组中的结束位置变量索引
    var _indexEnd = null;
    // 将jsonString字符串内容通过\r\n符分割成数组
    var jsonArray = [];
    // 正则匹配到{,}符号则在两边添加回车换行
    jsonString = jsonString.replace(/([\{\}])/g, '\r\n$1\r\n');
    // 正则匹配到[,]符号则在两边添加回车换行
    jsonString = jsonString.replace(/([\[\]])/g, '\r\n$1\r\n');
    // 正则匹配到,符号则在两边添加回车换行
    jsonString = jsonString.replace(/(\,)/g, '$1\r\n');
    // 正则匹配到要超过一行的换行需要改为一行
    jsonString = jsonString.replace(/(\r\n\r\n)/g, '\r\n');
    // 正则匹配到单独处于一行的,符号时需要去掉换行，将,置于同行
    jsonString = jsonString.replace(/\r\n\,/g, ',');
    // 特殊处理双引号中的内容
    jsonArray = jsonString.split('\r\n');
    jsonArray.forEach(function (node, index) {
      // 获取当前字符串段中"的数量
      var num = node.match(/\"/g) ? node.match(/\"/g).length : 0;
      // 判断num是否为奇数来确定是否需要特殊处理
      if (num % 2 && !_indexStart) {
        _indexStart = index;
      }
      if (num % 2 && _indexStart && _indexStart != index) {
        _indexEnd = index;
      }
      // 将需要特殊处理的字符串段的其实位置和结束位置信息存入，并对应重置开始时和结束变量
      if (_indexStart && _indexEnd) {
        _index.push({
          start: _indexStart,
          end: _indexEnd
        });
        _indexStart = null;
        _indexEnd = null;
      }
    });
    // 开始处理双引号中的内容，将多余的"去除
    _index.reverse().forEach(function (item, index) {
      var newArray = jsonArray.slice(item.start, item.end + 1);
      jsonArray.splice(item.start, item.end + 1 - item.start, newArray.join(''));
    });
    // 奖处理后的数组通过\r\n连接符重组为字符串
    jsonString = jsonArray.join('\r\n');
    // 将匹配到:后为回车换行加大括号替换为冒号加大括号
    jsonString = jsonString.replace(/\:\r\n\{/g, ':{');
    // 将匹配到:后为回车换行加中括号替换为冒号加中括号
    jsonString = jsonString.replace(/\:\r\n\[/g, ':[');
    // 将上述转换后的字符串再次以\r\n分割成数组
    jsonArray = jsonString.split('\r\n');
    // 将转换完成的字符串根据PADDING值来组合成最终的形态
    jsonArray.forEach(function (item, index) {
      var i = 0;
      // 表示缩进的位数，以tab作为计数单位
      var indent = 0;
      // 表示缩进的位数，以空格作为计数单位
      var padding = '';
      if (item.match(/\{$/) || item.match(/\[$/)) {
        // 匹配到以{和[结尾的时候indent加1
        indent += 1;
      } else if (item.match(/\}$/) || item.match(/\]$/) || item.match(/\},$/) || item.match(/\],$/)) {
        // 匹配到以}和]结尾的时候indent减1
        if (pad !== 0) {
          pad -= 1;
        }
      } else {
        indent = 0;
      }
      for (i = 0; i < pad; i++) {
        padding += PADDING;
      }
      formatted += padding + item + '\r\n';
      pad += indent;
    });
    // 返回的数据需要去除两边的空格
    return formatted.trim();
  }
</script>
</body>
</html>
